package lee.vioson.ebook.ui.components

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.KeyboardArrowLeft
import androidx.compose.material.icons.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import androidx.navigation.NavHostController
import lee.vioson.ebook.R
import lee.vioson.ebook.data.AppContainer
import lee.vioson.ebook.ui.AppDestinations
import lee.vioson.ebook.ui.AppTheme
import lee.vioson.ebook.viewmodels.ReadViewModel
import lee.vioson.remotedata.bean.BookData
import lee.vioson.remotedata.bean.Chapter
import lee.vioson.remotedata.bean.ChapterInfo
import lee.vioson.remotedata.bean.boolean

/**
 *Author:viosonlee
 *Date:2023/6/2
 *DESCRIPTION:
 */
@Composable
fun ReadScreen(
    chapter: Chapter,
    book: BookData,
    navHostController: NavHostController,
    appContainer: AppContainer,
    viewModel: ReadViewModel = viewModel(factory = viewModelFactory {
        initializer {
            ReadViewModel(appContainer, chapter, book)
        }
    })
) {
    LaunchedEffect(key1 = Unit, block = {
        viewModel.addBookReadHistory()
    })
    val state by viewModel.state.collectAsState()
    LaunchedEffect(key1 = state.chapter, block = {
        viewModel.chapterInfoList(state.chapter)
    })
    Box(Modifier.fillMaxSize()) {
        Reader(appContainer, state.chapterInfoList, book.bookInfo.id, modifier = Modifier
            .fillMaxSize()
            .pointerInput(key1 = Unit) {
                detectTapGestures(
                    onTap = {
                        viewModel.sendEvent(ReadViewModel.Event.OnToggleController(!state.showController))
                    }
                )
            })
        if (state.showController) {
            Column(Modifier.fillMaxSize()) {
                Title(
                    title = chapter.chapterName,
                    isCollection = state.isCollection,
                    collectionLoading = state.collectionLoading,
                    navHostController = navHostController
                ) {
                    viewModel.addCollection(it)
                }
                Spacer(modifier = Modifier.weight(1f))
                if (state.showList) {
                    LazyColumn(
                        modifier = Modifier
                            .heightIn(max = 500.dp)
                            .background(AppTheme.colors.background), content = {
                            items(book.chapterList) { item ->
                                ChapterItem(
                                    item,
                                    book
                                ) {
                                    //change to read this chapter
                                    if (item.isVip.boolean) {
                                        navHostController.navigate(AppDestinations.VIP_SCREEN)
                                    } else {
                                        viewModel.sendEvent(ReadViewModel.Event.OnChapterChange(item))
                                    }
                                }
                            }
                        })
                }
                BottomController(state, viewModel, book)
            }
        }
    }
}

@Composable
private fun Reader(
    appContainer: AppContainer,
    chapterInfoList: List<ChapterInfo>,
    bookId: String,
    modifier: Modifier = Modifier
) {
    LazyColumn(modifier = modifier, content = {
        items(chapterInfoList) { chapter: ChapterInfo ->
            ReadPage(appContainer, bookId, chapterInfo = chapter)
        }
    })
}


@Composable
private fun Title(
    title: String,
    isCollection: Boolean,
    collectionLoading: Boolean,
    navHostController: NavHostController,
    onCollectionChange: (Boolean) -> Unit
) {
    Row(
        Modifier
            .fillMaxWidth()
            .background(Color.Black.copy(0.5f))
            .statusBarsPadding()
            .height(48.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = title,
            fontSize = 14.sp,
            color = AppTheme.appColors.whiteText80,
            modifier = Modifier
                .weight(1f)
                .padding(start = 8.dp),
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
        Loading(showLoading = collectionLoading) {
            Image(
                painter = painterResource(
                    id = if (isCollection) R.mipmap.ic_collected
                    else R.mipmap.ic_add_collect
                ),
                contentDescription = "collection button",
                modifier = Modifier
                    .size(24.dp)
                    .clickable {
                        onCollectionChange(!isCollection)
                    }
            )
        }
        Icon(
            imageVector = Icons.Default.ArrowBack, contentDescription = "back button",
            modifier = Modifier
                .size(48.dp)
                .clickable { navHostController.popBackStack() }
                .padding(8.dp),
            tint = AppTheme.appColors.whiteText80
        )
    }
}


@Composable
fun BottomController(state: ReadViewModel.State, viewModel: ReadViewModel, book: BookData) {
    Row(
        Modifier
            .fillMaxWidth()
            .background(Color.Black.copy(0.5f))
            .navigationBarsPadding(),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceAround
    ) {
        Icon(
            imageVector = Icons.Default.KeyboardArrowLeft, contentDescription = "Previous section",
            modifier = Modifier
                .clickable {
                    viewModel.onPrevious(book.chapterList, state.chapter)
                }
                .padding(8.dp)
                .size(48.dp),
            tint = AppTheme.colors.onBackground
        )
        Icon(
            imageVector = Icons.Default.Menu, contentDescription = "setting",
            modifier = Modifier
                .clickable {
                    viewModel.sendEvent(ReadViewModel.Event.OnToggleChapterList(!state.showList))
                }
                .padding(8.dp)
                .size(48.dp),
            tint = AppTheme.colors.onBackground
        )
        Icon(
            imageVector = Icons.Default.KeyboardArrowRight,
            contentDescription = "Next section",
            modifier = Modifier
                .clickable {
                    viewModel.onNext(book.chapterList, state.chapter)
                }
                .padding(8.dp)
                .size(48.dp),
            tint = AppTheme.colors.onBackground
        )
    }
}